package com.syp.test.clustercacheflush.service;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.syp.test.clustercacheflush.dao.SettingsRepository;
import com.syp.test.clustercacheflush.domain.SettingsEntity;
import com.syp.test.clustercacheflush.domain.TaskEntity;
import com.syp.test.clustercacheflush.util.zkflushcache.CacheFlushDispacher;

@Service
public class SettingsService implements CacheFlushDispacher, InitializingBean {

	private static final ConcurrentHashMap<String, SettingsEntity> cache = new ConcurrentHashMap<>();

	@Autowired
	private SettingsRepository settingsRepository;
	@Autowired
	private TaskService taskService;

	public SettingsEntity get(String key) {
		return cache.get(key);
	}

	@Transactional(rollbackFor = { RuntimeException.class })
	public void save(SettingsEntity setting) {
		this.settingsRepository.save(setting);
	}

	@Transactional(rollbackFor = { RuntimeException.class })
	public void save(SettingsEntity setting, TaskEntity task) {
		this.settingsRepository.save(setting);
		this.taskService.save(task);
	}

	@Override
	public void flushCache(String key) {
		SettingsEntity st = this.settingsRepository.getByKey(key);
		cache.put(key, st);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		List<SettingsEntity> allSettings = this.settingsRepository.findAll();
		if (allSettings != null && !allSettings.isEmpty()) {
			allSettings.forEach(st -> {
				cache.put(st.getKey(), st);
			});
		}

	}

}
